import React, {Component} from 'react';
import {Space, Select, Card, Tooltip, Statistic, Typography, Modal, message} from "antd";
import {QuestionCircleFilled} from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheButton from "@/components/TheButton";
import TheQueryForm from '@/components/TheQueryForm';
import {exportSheetTable} from '@/utils/exportTable.js';
import {
    apiGetProviderList,
    apiGetAccountPrice,
    apiGetServicerCashFlow,
    apiExportServicerCashFlow
} from '@/request/callReconciliation/accountManage.js';
import _ from 'lodash'
import moment from 'moment'
import TweenOne from 'rc-tween-one';
import ChildrenPlugin from 'rc-tween-one/lib/plugin/ChildrenPlugin';

TweenOne.plugins.push(ChildrenPlugin);

const {Paragraph} = Typography;

//账户管理
export default class AccountManage extends Component {
    state = {
        options: [],
        columns: [
            {
                title: "申请编号",
                dataIndex: "servicerCashFlowId",
                key: "servicerCashFlowId",
                width: 300
            },
            {
                title: "服务者id",
                dataIndex: "providerId",
                key: "providerId",
                width: 260
            },
            {
                title: "服务者",
                dataIndex: "providerName",
                key: "providerName",
                width: 260
            },
            {
                title: "类型",
                dataIndex: "businessType",
                key: "businessType",
                render: (text, record) => {
                    let label = ''
                    switch (text) {
                        case 1:
                            label = '服务收入'
                            break
                        case 2:
                            label = '违约赔偿'
                            break
                        case 3:
                            label = '提现'
                            break
                        default:
                            label = '-'
                            break
                    }
                    return label
                }
            },
            {
                title: "金额(元)",
                dataIndex: "price",
                key: "price",
                render: (text) => {
                    return <React.$Price price={text}/>
                }
            },
            {
                title: "申请状态",
                dataIndex: "auditState",
                key: "auditState",
                render: (text, record) => {
                    let label = ''
                    switch (text) {
                        case 0:
                            label = '审核中'
                            break
                        case 1:
                            label = '通过'
                            break
                        case 2:
                            label = '通过'
                            break
                        case 3:
                            label = (
                                <Space>
                                    <span>驳回</span>
                                    <Tooltip title={record.rejectReason}>
                                        <QuestionCircleFilled/>
                                    </Tooltip>
                                </Space>
                            )
                            break
                    }
                    return label
                }
            },
            {
                title: "申请时间",
                dataIndex: "applyTime",
                key: "applyTime",
                width: 200
            },
            {
                title: "备注",
                dataIndex: "remark",
                key: "remark",
                width: 200
            },
            {
                title: "提现状态",
                dataIndex: "payState",
                key: "payState",
                render: (text, record) => {
                    let label = ''
                    switch (text) {
                        case 0:
                            label = '提现中'
                            break
                        case 1:
                            label = '成功'
                            break
                        case 2:
                            label = '失败'
                            break
                    }
                    return label
                }
            },
            {
                title: "流水编号",
                dataIndex: "payCode",
                key: "payCode",
                width: 200,
                render: (text, record) => {
                    if (record.auditState === 2 || record.payState === 2 || !text) {
                        return '-'
                    }
                    return text
                }
            },
        ],
        dataSource: [],
        pageData: {
            pageNo: 1,
            pageSize: 10,
        },
        total: 0,
        form_show: true,
        searchOption: [
            {
                field: 'servicerCashFlowId',
                label: '申请编号',
                placeholder: '请输入',
                required: false,
                rules: [],
                type: 'Input',
                defaultValue: ''
            },
            {
                field: 'payCode',
                label: '流水编号',
                placeholder: '请输入',
                required: false,
                rules: [],
                type: 'Input',
                defaultValue: ''
            },
            {
                field: 'auditStateList',
                label: '申请状态',
                placeholder: '请选择',
                required: false,
                rules: [],
                type: 'Select',
                options: [
                    {value: '', label: '全部'},
                    {value: '0', label: '审核中'},
                    {value: '1,2', label: '通过'},
                    {value: '3', label: '驳回'}
                ],
                defaultValue: ''
            },
            {
                field: 'payState',
                label: '提现状态',
                placeholder: '请选择',
                required: false,
                rules: [],
                type: 'Select',
                options: [
                    {value: '', label: '全部'},
                    {value: 0, label: '提现中'},
                    {value: 1, label: '成功'},
                    {value: 2, label: '失败'}
                ],
                defaultValue: ''
            },
            {
                field: 'time',
                label: '申请时间',
                placeholder: '请选择',
                required: false,
                rules: [],
                type: 'RangePicker'
            },
        ],
        providerIdList: [],//选择的服务者店铺id
        queryForm: {},
        alreadyWithdrawPrice: '', //已提现金额
        canWithdrawPrice: '', // 可提现金额
        waitSettledPrice: '',//待结算金额
        alreadySettledPrice: '',//已结算金额
        exportLoading: false, //导出loading
    }

    componentDidMount() {
        this.getProviderList()
        this.getAccountPrice(null)
        this.getServicerCashFlow()
    }

    // 服务者下拉列表
    getProviderList = async () => {
        let res = await apiGetProviderList()
        if (res.code === 0 && res.data) {
            const newArr = res.data.map(item => {
                return {
                    label: item.name + '-' + item.providerId,
                    value: item.providerId
                }
            })
            this.setState({options: newArr})
        }
    }
    servicerHandleChange = (e) => {
        this.setState({providerIdList: e})
        this.getAccountPrice(e)
        this.pageChange(1, 10)
    }
    // 商家账户金额汇总
    getAccountPrice = async (idList) => {
        let res = await apiGetAccountPrice({providerIdList: idList})
        if (res.code === 0 && res.data) {
            this.setState({
                alreadyWithdrawPrice: res.data.alreadyWithdrawPrice ? React.$transNum(res.data.alreadyWithdrawPrice, 2, -2) : 0,
                canWithdrawPrice: res.data.canWithdrawPrice ? React.$transNum(res.data.canWithdrawPrice, 2, -2) : 0,
                waitSettledPrice: res.data.waitSettledPrice ? React.$transNum(res.data.waitSettledPrice, 2, -2) : 0,
                alreadySettledPrice: res.data.alreadySettledPrice ? React.$transNum(res.data.alreadySettledPrice, 2, -2) : 0,
            })
        }
    }
    // 商家资金流水明细
    getServicerCashFlow = async () => {
        const {providerIdList, pageData, queryForm} = this.state
        let params = {
            ...pageData,
            ...queryForm,
            providerIdList,
            businessType: 3 // 业务类型： 3-提现（提现固定传3），必填
        }
        let res = await apiGetServicerCashFlow({...params})
        if (res.code === 0) {
            this.setState({
                dataSource: res.data,
                pageNo: res.pageNo,
                pageSize: res.pageSize,
                total: res.totalCount
            })
        }
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {pageNo, pageSize}
        }, () => {
            this.getServicerCashFlow()
        })
    };

    /**
     * @desc 表格搜索组件重置搜索条件
     * */
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }

    /**
     * @desc 表格搜索组件搜索
     * */
    onFormSearch(value) {
        if (value && value.hasOwnProperty('time')) {
            value.applyBeginTime = moment(value.time[0]).format('yyyy-MM-DD') + ' 00:00:00'
            value.applyEndTime = moment(value.time[1]).format('yyyy-MM-DD') + ' 23:59:59'
            delete value.time
        }
        if (value && value.hasOwnProperty('auditStateList')) {
            value.auditStateList = value.auditStateList.split(',').map(item => Number(item))
        }
        this.setState({
            pageData: {pageNo: 1, pageSize: 10},
            queryForm: {...value}
        }, () => {
            this.getServicerCashFlow()
        })
    }

    /**
     * @desc 表格数据导出
     * */
    toExport = async () => {
        const {providerIdList, queryForm} = this.state

        if (_.isEmpty(queryForm)) {
            Modal.warning({title: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。',});
            return
        }
        this.setState({exportLoading: true})
        let params = {
            ...queryForm,
            providerIdList,
            businessType: 3,
        }
        let res = await apiExportServicerCashFlow({...params})
        if (res.code === 0) {
            let th_arr = [
                {
                    title: '服务者资金流水明细',
                    prop: '',
                    children: [
                        {
                            title: "申请编号",
                            prop: "servicerCashFlowId",
                        },
                        {
                            title: "服务者id",
                            prop: "providerId",
                        },
                        {
                            title: "服务者",
                            prop: "providerName",
                        },
                        {
                            title: "类型",
                            prop: "businessType",
                        },
                        {
                            title: "金额(元)",
                            prop: "price",
                        },
                        {
                            title: "申请状态",
                            prop: "auditState",
                        },
                        {
                            title: "申请时间",
                            prop: "applyTime",
                        },
                        {
                            title: "备注",
                            prop: "remark",
                        },
                        {
                            title: "提现状态",
                            prop: "payState",
                        },
                        {
                            title: "流水编号",
                            prop: "payCode",
                        },
                    ]
                },
            ]
            let tb_arr = []
            res.data.forEach((item, index) => {
                let auditState = ''
                let payState = ''
                //审核状态
                switch (item.auditState) {
                    case 0:
                        auditState = '审核中'
                        break
                    case 1:
                        auditState = '通过'
                        break
                    case 2:
                        auditState = '通过'
                        break
                    case 3:
                        auditState = '驳回 '
                        break
                }
                //提现状态
                switch (item.payState) {
                    case 0:
                        payState = '提现中'
                        break
                    case 1:
                        payState = '成功'
                        break
                    case 2:
                        payState = '失败 '
                        break
                }
                tb_arr.push({
                    ...item,
                    index: index + 1,
                    payState: payState,
                    auditState: auditState,
                    price: '￥' + (React.$transNum(item.price, 2, -2)) || '￥0.00',
                    businessType: '提现'
                })
            })
            exportSheetTable({
                fileName: '服务者资金流水明细',
                tH_data: th_arr,
                tB_data: tb_arr,
                isSheet: true,
                merge: false
            })
        }
        this.setState({exportLoading: false})
    }

    render() {
        let {
            options,
            columns,
            dataSource,
            pageData: {pageNo, pageSize},
            total,
            searchOption,
            form_show,
            alreadyWithdrawPrice, //已提现金额
            canWithdrawPrice, // 可提现金额
            waitSettledPrice,//待结算金额
            alreadySettledPrice,//已结算金额
        } = this.state
        return (
            <div className={"p-layout-box commodity-content"}>
                <Paragraph strong style={{margin: 0}}>
                    <blockquote>服务者账户金额汇总</blockquote>
                </Paragraph>
                <Space style={{marginBottom: 20, paddingLeft: 15}}>
                    <span style={{fontSize: 14}}>服务者：</span>
                    <Select
                        mode="multiple"
                        allowClear
                        style={{width: '280px'}}
                        placeholder="全部"
                        onChange={this.servicerHandleChange}
                        options={options}
                        filterOption={(input, option) => (option?.label ?? '').includes(input)}
                    />
                </Space>
                <Space align={"center"} size={30}>
                    <Card
                        style={{width: 300}}
                        title="可提现金额"
                        extra={
                            <Tooltip title="可提现金额 = 累计结算金额  减去 已提现到账、提现中且未到账的金额之和">
                                <QuestionCircleFilled style={{fontSize: 20}}/>
                            </Tooltip>
                        }
                    >
                        <Space style={{fontSize: 28}}>
                            <span>¥</span>
                            <TweenOne
                                animation={{
                                    Children: {value: canWithdrawPrice, floatLength: 2, formatMoney: true}
                                }}
                            />
                        </Space>
                    </Card>
                    <Card
                        style={{width: 300}}
                        title="累计提现金额"
                        extra={
                            <Tooltip title="所选服务者累计提现到账的金额">
                                <QuestionCircleFilled style={{fontSize: 20}}/>
                            </Tooltip>
                        }
                    >
                        <Space style={{fontSize: 28}}>
                            <span>¥</span>
                            <TweenOne
                                animation={{
                                    Children: {value: alreadyWithdrawPrice, floatLength: 2, formatMoney: true}
                                }}
                            />
                        </Space>
                    </Card>
                    <Card
                        style={{width: 300}}
                        title="待结算金额"
                        extra={
                            <Tooltip
                                title="今日0点及之后所有未结算（状态为待服务、服务中、已完成）服务订单的金额之和+消费者有责待结算退款金额之和">
                                <QuestionCircleFilled style={{fontSize: 20}}/>
                            </Tooltip>
                        }
                    >
                        <Space style={{fontSize: 28}}>
                            <span>¥</span>
                            <TweenOne
                                animation={{
                                    Children: {value: waitSettledPrice, floatLength: 2, formatMoney: true}
                                }}
                            />
                        </Space>
                    </Card>
                    <Card
                        style={{width: 300}}
                        title="累计结算金额"
                        extra={
                            <Tooltip title="该服务者服务订单行结算状态为已结算的服务者所得金额之和">
                                <QuestionCircleFilled style={{fontSize: 20}}/>
                            </Tooltip>
                        }
                    >
                        <Space style={{fontSize: 28}}>
                            <span>¥</span>
                            <TweenOne
                                animation={{
                                    Children: {value: alreadySettledPrice, floatLength: 2, formatMoney: true}
                                }}
                            />
                        </Space>
                    </Card>
                </Space>
                <Paragraph strong style={{margin: 0}}>
                    <blockquote>服务者资金流水明细</blockquote>
                </Paragraph>
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                              onGetValues={(values) => this.onFormSearch(values)}
                              onReset={(values) => this.onReset(values)}
                >
                    <TheButton haspermi={['call:financialReconcile:accountManage:export']} size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
                </TheQueryForm>
                <TheTable
                    scroll={{x: "960", y: '63vh'}}
                    columns={columns}
                    dataSource={dataSource}
                    rowKey={'storeCashFlowCommissionId'}
                />
                <ThePagination
                    pageNo={pageNo}
                    pageSize={pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
            </div>
        );
    }
}
